<template>
    <view class="container">
        <view class="question-card">
            <!-- 题目内容 -->
            <view class="question-title">
                <text class="title-text">{{ question.title }}</text>
            </view>
            <image v-if="question.titlePic" :src="question.titlePic" mode="aspectFit" class="question-image"></image>

            <!-- 选项列表 -->
            <view class="options-list">
                <view v-for="(option, key) in options" :key="key" class="option-item" :class="{
                    'selected': selectedAnswer === key,
                    'correct': showAnswer && answer === key,
                    'wrong': showAnswer && selectedAnswer === key && selectedAnswer !== answer
                }" @click="selectAnswer(key)">
                    {{ option }}
                </view>
            </view>

            <!-- 操作按钮 -->
            <view class="action-buttons">
                <button class="btn submit" @click="submitAnswer" v-if="!showAnswer">提交答案</button>
                <button class="btn next" @click="nextQuestion" v-else>下一题</button>
            </view>

            <!-- 答案解析 -->
            <view class="answer-analysis" v-if="showAnswer">
                <view class="analysis-title">答案解析</view>
                <view class="analysis-content">{{ explain }}</view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            questionId: '',
            question: {},
            options: {},
            selectedAnswer: '',
            answer: '',
            explain: '',
            showAnswer: false,
            appId: 'jijnkniwlmswemjf',
            appSecret: 'og1FoKNxT0IJMZNdb1UYkcidZBwTjgeE',
            score: 0,
            totalQuestions: 0,
            correctAnswers: 0
        }
    },
    onLoad(option) {
        this.questionId = option.id
        this.loadQuestionDetail()
        // 从本地存储加载分数记录
        const scoreData = uni.getStorageSync('examScore') || { score: 0, totalQuestions: 0, correctAnswers: 0 }
        this.score = scoreData.score
        this.totalQuestions = scoreData.totalQuestions
        this.correctAnswers = scoreData.correctAnswers
    },
    methods: {
        async loadQuestionDetail() {
            try {
                // 获取题目详情
                const url = `https://www.mxnzp.com/api/driver_exam/answer/list?ids=${this.questionId}&app_id=${this.appId}&app_secret=${this.appSecret}`
                const res = await uni.request({
                    url,
                    method: 'GET'
                })

                if (res.data.code === 1) {
                    const answerData = res.data.data[0]
                    this.answer = answerData.answer
                    this.explain = answerData.explain

                    // 获取题目内容
                    const questionData = this.getQuestionFromStorage(this.questionId)
                    if (questionData) {
                        this.question = questionData
                        this.formatOptions(questionData)
                    }
                } else {
                    uni.showToast({
                        title: '获取答案失败',
                        icon: 'none'
                    })
                }
            } catch (e) {
                uni.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                })
            }
        },
        getQuestionFromStorage(id) {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage) {
                return prevPage.$vm.questionList.find(q => q.id === parseInt(id))
            }
            return null
        },
        formatOptions(question) {
            this.options = {}
            if (question.op1) this.options.A = question.op1
            if (question.op2) this.options.B = question.op2
            if (question.op3) this.options.C = question.op3
            if (question.op4) this.options.D = question.op4
        },
        selectAnswer(key) {
            if (!this.showAnswer) {
                this.selectedAnswer = key
            }
        },
        submitAnswer() {
            if (!this.selectedAnswer) {
                uni.showToast({
                    title: '请选择答案',
                    icon: 'none'
                })
                return
            }
            this.showAnswer = true
            this.saveExamRecord()
        },
        saveExamRecord() {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]

            // 获取当前题目的分类信息
            let currentRank, currentType
            if (this.options.from === 'wrong') {
                currentRank = this.options.rank
                currentType = this.options.type
            } else if (prevPage) {
                currentRank = prevPage.$vm.rankList[prevPage.$vm.rankIndex].id
                currentType = prevPage.$vm.typeList[prevPage.$vm.typeIndex].id
            }

            if (currentRank && currentType) {
                // 保存答题记录
                const storageKey = `examScore_${currentRank}_${currentType}`
                const examRecord = uni.getStorageSync(storageKey) || {
                    score: 0,
                    totalQuestions: 0,
                    correctAnswers: 0
                }

                examRecord.totalQuestions++
                if (this.selectedAnswer === this.answer) {
                    examRecord.correctAnswers++
                    examRecord.score += 1
                } else {
                    // 如果答错了，添加到错题本
                    const wrongStorageKey = `wrongQuestions_${currentRank}_${currentType}`
                    const wrongQuestions = uni.getStorageSync(wrongStorageKey) || []
                    const questionData = this.getQuestionFromStorage(this.questionId)
                    if (questionData && !wrongQuestions.find(q => q.id === questionData.id)) {
                        wrongQuestions.push({
                            ...questionData,
                            reviewed: false
                        })
                        uni.setStorageSync(wrongStorageKey, wrongQuestions)
                    }
                }

                uni.setStorageSync(storageKey, examRecord)
            }
        },
        nextQuestion() {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage) {
                const currentIndex = prevPage.$vm.questionList.findIndex(q => q.id === parseInt(this.questionId))
                if (currentIndex < prevPage.$vm.questionList.length - 1) {
                    const nextQuestion = prevPage.$vm.questionList[currentIndex + 1]
                    this.questionId = nextQuestion.id
                    this.question = nextQuestion
                    this.formatOptions(nextQuestion)
                    this.selectedAnswer = ''
                    this.showAnswer = false
                    this.loadQuestionDetail()
                } else {
                    uni.showToast({
                        title: '已经是最后一题',
                        icon: 'none'
                    })
                }
            }
        }
    }
}
</script>

<style>
.container {
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.question-card {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
}

.question-title {
    margin-bottom: 30rpx;
}

.title-text {
    font-size: 32rpx;
    color: #333;
    line-height: 1.5;
}

.question-image {
    width: 100%;
    height: 300rpx;
    margin-bottom: 30rpx;
}

.options-list {
    margin-bottom: 40rpx;
}

.option-item {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
    padding: 20rpx;
    border: 2rpx solid #eee;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
}

.option-item.selected {
    background-color: #e1f3ff;
    border-color: #40a9ff;
}

.option-item.correct {
    background-color: #f6ffed;
    border-color: #52c41a;
}

.option-item.wrong {
    background-color: #fff1f0;
    border-color: #ff4d4f;
}

.action-buttons {
    margin-bottom: 30rpx;
}

.btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 8rpx;
    font-size: 28rpx;
}

.btn.submit {
    background-color: #40a9ff;
    color: #fff;
}

.btn.next {
    background-color: #52c41a;
    color: #fff;
}

.answer-analysis {
    border-top: 2rpx solid #eee;
    padding-top: 30rpx;
}

.analysis-title {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.analysis-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
}
</style>